package com.yixueyun.learning.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yixueyun.base.exception.YiXueYunPlusException;
import com.yixueyun.base.model.PageResult;
import com.yixueyun.content.model.po.CoursePublish;
import com.yixueyun.learning.feignclient.ContentServiceClient;
import com.yixueyun.learning.mapper.YxyChooseCourseMapper;
import com.yixueyun.learning.mapper.YxyCourseTablesMapper;
import com.yixueyun.learning.model.dto.MyCourseTableParams;
import com.yixueyun.learning.model.dto.YxyChooseCourseDto;
import com.yixueyun.learning.model.dto.YxyCourseTablesDto;
import com.yixueyun.learning.model.po.YxyChooseCourse;
import com.yixueyun.learning.model.po.YxyCourseTables;
import com.yixueyun.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {
    @Autowired
    private YxyCourseTablesMapper yxyCourseTablesMapper;
    @Autowired
    private YxyChooseCourseMapper yxyChooseCourseMapper;
    @Autowired
    private ContentServiceClient contentServiceClient;
    /**
     *添加选课
     * @param userId 用户id
     * @param courseId 课程id
     * @return
     */
    @Override
    @Transactional
    public YxyChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //远程调用，查询课程是否收费
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        String charge = coursepublish.getCharge();
        YxyChooseCourse yxyChooseCourse = null;
        if(charge.equals("201000")) {
            //免费，向选课表，课程表写入数据
            //向选课记录表插入数据
            yxyChooseCourse = addFreeCoruse(userId, coursepublish);
            //向课程表插入数据
            YxyCourseTables yxyCourseTables = addCourseTables(yxyChooseCourse);
        } else {
            //收费，向选课表写入数据
            yxyChooseCourse = addChargeCoruse(userId, coursepublish);
        }
        //判断学生学习资格
        YxyCourseTablesDto learningStatus = getLearningStatus(userId, courseId);
        YxyChooseCourseDto yxyChooseCourseDto = new YxyChooseCourseDto();
        BeanUtils.copyProperties(yxyChooseCourse, yxyChooseCourseDto);
        yxyChooseCourseDto.setLearnStatus(learningStatus.getLearnStatus());
        return yxyChooseCourseDto;
    }

    /**
     * 获取学习资格
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public YxyCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //查询我的课程表
        YxyCourseTables yxyCourseTables = getYxyCourseTables(userId, courseId);
        //没有选课或选课后没有支付
        if(yxyCourseTables ==null){
            YxyCourseTablesDto yxyCourseTablesDto = new YxyCourseTablesDto();
            //没有选课或选课后没有支付
            yxyCourseTablesDto.setLearnStatus("702002");
            return yxyCourseTablesDto;
        }
        YxyCourseTablesDto yxyCourseTablesDto = new YxyCourseTablesDto();
        BeanUtils.copyProperties(yxyCourseTables, yxyCourseTablesDto);
        //是否过期,true过期，false未过期
        boolean isExpires = yxyCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if(!isExpires){
            //正常学习
            yxyCourseTablesDto.setLearnStatus("702001");
            return yxyCourseTablesDto;

        }else{
            //已过期
            yxyCourseTablesDto.setLearnStatus("702003");
            return yxyCourseTablesDto;
        }
    }

    /**
     * 保存选课信息
     * @param chooseCourseId
     * @return
     */
    @Override
    public boolean saveChooseCourseSuccess(String chooseCourseId) {
        //根据id查询数据库，判断是否在我的选课中
        YxyChooseCourse yxyChooseCourse = yxyChooseCourseMapper.selectById(chooseCourseId);
        if(yxyChooseCourse == null) {
            log.debug("接收到购买课程信息的消息，但是找不到选课记录，选课id：{}",chooseCourseId);
            return false;
        }
        String status = yxyChooseCourse.getStatus();
        //当未支付时，才更新为已支付
        if(status.equals("701002")) {
            //更新状态。
            yxyChooseCourse.setStatus("701001");
            int i = yxyChooseCourseMapper.updateById(yxyChooseCourse);
            if(i <= 0) {
                log.debug("添加选课失败，{}", yxyChooseCourse);
                YiXueYunPlusException.cast("添加选课记录失败");
            }
            //向课程表中添加记录
            YxyCourseTables yxyCourseTables = addCourseTables(yxyChooseCourse);
        }
        return true;
    }

    //添加免费课程,免费课程加入选课记录表、我的课程表
    public YxyChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
        //判断是否存在选课记录，且选课状态为成功，存在直接返回
        //得到课程id
        Long courseId = coursepublish.getId();
        LambdaQueryWrapper<YxyChooseCourse> queryWrapper = new LambdaQueryWrapper<YxyChooseCourse>()
                .eq(YxyChooseCourse::getCourseId, courseId)
                .eq(YxyChooseCourse::getUserId, userId)
                .eq(YxyChooseCourse::getOrderType, "700001")//课程类型
                .eq(YxyChooseCourse::getStatus, "701001");//选课状态
        List<YxyChooseCourse> yxyChooseCourses = yxyChooseCourseMapper.selectList(queryWrapper);
        if( yxyChooseCourses.size() > 0) {
            return yxyChooseCourses.get(0);
        }
        //添加选课记录信息
        YxyChooseCourse yxyChooseCourse = new YxyChooseCourse();
        yxyChooseCourse.setCourseId(coursepublish.getId());
        yxyChooseCourse.setCourseName(coursepublish.getName());
        yxyChooseCourse.setCoursePrice(0f);//免费课程价格为0
        yxyChooseCourse.setUserId(userId);
        yxyChooseCourse.setCompanyId(coursepublish.getCompanyId());
        yxyChooseCourse.setOrderType("700001");//免费课程
        yxyChooseCourse.setCreateDate(LocalDateTime.now());
        yxyChooseCourse.setStatus("701001");//选课成功

        yxyChooseCourse.setValidDays(365);//免费课程默认365
        yxyChooseCourse.setValidtimeStart(LocalDateTime.now());
        yxyChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        yxyChooseCourseMapper.insert(yxyChooseCourse);

        return yxyChooseCourse;

    }
    //添加到我的课程表
    public YxyCourseTables addCourseTables(YxyChooseCourse yxyChooseCourse){
        //选课记录完成且未过期可以添加课程到课程表
        String status = yxyChooseCourse.getStatus();
        if (!"701001".equals(status)){
            YiXueYunPlusException.cast("选课未成功，无法添加到课程表");
        }
        //查询我的课程表
        YxyCourseTables yxyCourseTables = getYxyCourseTables(yxyChooseCourse.getUserId(), yxyChooseCourse.getCourseId());
        if(yxyCourseTables !=null){
            return yxyCourseTables;
        }
        YxyCourseTables yxyCourseTablesNew = new YxyCourseTables();
        yxyCourseTablesNew.setChooseCourseId(yxyChooseCourse.getId());
        yxyCourseTablesNew.setUserId(yxyChooseCourse.getUserId());
        yxyCourseTablesNew.setCourseId(yxyChooseCourse.getCourseId());
        yxyCourseTablesNew.setCompanyId(yxyChooseCourse.getCompanyId());
        yxyCourseTablesNew.setCourseName(yxyChooseCourse.getCourseName());
        yxyCourseTablesNew.setCreateDate(LocalDateTime.now());
        yxyCourseTablesNew.setValidtimeStart(yxyChooseCourse.getValidtimeStart());
        yxyCourseTablesNew.setValidtimeEnd(yxyChooseCourse.getValidtimeEnd());
        yxyCourseTablesNew.setCourseType(yxyChooseCourse.getOrderType());
        int insert = yxyCourseTablesMapper.insert(yxyCourseTablesNew);
        if( insert <= 0 ) {
            YiXueYunPlusException.cast("添加到课程表失败");
        }
        return yxyCourseTablesNew;
    }
    //添加收费课程
    public YxyChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish){
        //如果存在待支付交易记录直接返回
        LambdaQueryWrapper<YxyChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(YxyChooseCourse::getUserId, userId)
                .eq(YxyChooseCourse::getCourseId, coursepublish.getId())
                .eq(YxyChooseCourse::getOrderType, "700002")//收费订单
                .eq(YxyChooseCourse::getStatus, "701002");//待支付
        List<YxyChooseCourse> yxyChooseCourses = yxyChooseCourseMapper.selectList(queryWrapper);
        if (yxyChooseCourses != null && yxyChooseCourses.size()>0) {
            return yxyChooseCourses.get(0);
        }

        YxyChooseCourse yxyChooseCourse = new YxyChooseCourse();
        yxyChooseCourse.setCourseId(coursepublish.getId());
        yxyChooseCourse.setCourseName(coursepublish.getName());
        yxyChooseCourse.setCoursePrice(coursepublish.getPrice());
        yxyChooseCourse.setUserId(userId);
        yxyChooseCourse.setCompanyId(coursepublish.getCompanyId());
        yxyChooseCourse.setOrderType("700002");//收费课程
        yxyChooseCourse.setCreateDate(LocalDateTime.now());
        yxyChooseCourse.setStatus("701002");//待支付

        yxyChooseCourse.setValidDays(coursepublish.getValidDays());
        yxyChooseCourse.setValidtimeStart(LocalDateTime.now());
        yxyChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
        yxyChooseCourseMapper.insert(yxyChooseCourse);
        return yxyChooseCourse;
    }
    /**
     * @description 根据课程和用户查询我的课程表中某一门课程
     * @param userId
     * @param courseId
     * @return com.yixueyun.learning.model.po.YxyCourseTables
     * @author kklmars
     * @date 2023/10/2 17:07
     */
    public YxyCourseTables getYxyCourseTables(String userId,Long courseId){
        YxyCourseTables yxyCourseTables = yxyCourseTablesMapper.selectOne(new LambdaQueryWrapper<YxyCourseTables>().eq(YxyCourseTables::getUserId, userId).eq(YxyCourseTables::getCourseId, courseId));
        return yxyCourseTables;

    }
    public PageResult<YxyCourseTables> mycourestabls(MyCourseTableParams params){
        //页码
        long pageNo = params.getPage();
        //每页记录数,固定为4
        long pageSize = 4;
        //分页条件
        Page<YxyCourseTables> page = new Page<>(pageNo, pageSize);
        //根据用户id查询
        String userId = params.getUserId();
        LambdaQueryWrapper<YxyCourseTables> lambdaQueryWrapper = new LambdaQueryWrapper<YxyCourseTables>().eq(YxyCourseTables::getUserId, userId);

        //分页查询
        Page<YxyCourseTables> pageResult = yxyCourseTablesMapper.selectPage(page, lambdaQueryWrapper);
        List<YxyCourseTables> records = pageResult.getRecords();
        //记录总数
        long total = pageResult.getTotal();
        PageResult<YxyCourseTables> courseTablesResult = new PageResult<>(records, total, pageNo, pageSize);
        return courseTablesResult;

    }
}
